//
//  AppDelegate.swift
//  WeoboWithSteveLi
//
//  Created by SteveLi on 2017/9/13.
//  Copyright © 2017年 李军桦. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        //测试归档的用户账户
        print(UserAccountViewModel.sharedUserAccount.account ?? "")
        
        
        setupApperarance()
        
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.backgroundColor = UIColor.white
        
        window?.rootViewController = defaultRootViewController
        //window?.rootViewController = WelcomeViewController()
        //window?.rootViewController = NewFeatureViewController()
       // window?.rootViewController = MainViewController()
        
        window?.makeKeyAndVisible()
        
        
        //监听通知
        NotificationCenter.default.addObserver(forName:
         WBSwitchRootViewControllerNotification, //通知名称，通知中心用来识别通知的
            object: nil,//发送通知的对象，如果为nil,监听任何对象
            queue: nil) //nil主线程
        { [weak self](notification) in
            print(Thread.current)
            print(notification)
            let vc = notification.object != nil ? WelcomeViewController() : MainViewController()
            
            //切换控制器
            self?.window?.rootViewController = vc
        }

        
        return true
    }
    
    deinit {
        //注销通知  --注销指定的通知
        NotificationCenter.default.removeObserver(self, name:WBSwitchRootViewControllerNotification , object: nil)
    }
    
    //设置全局外观 --- 在很多应用程序中，都会在AppDelegate中设置所有需要控件的全局外观
    func setupApperarance() {
        //修改导航栏的全局外观 要在控件创建前设置，一经设置全局有效
        UINavigationBar.appearance().tintColor = WEBAppearanceTinckColor
        UITabBar.appearance().tintColor = WEBAppearanceTinckColor
    }

}
//MARK: -界面切换代码
extension AppDelegate {
    /// 启动的根视图控制器
    var defaultRootViewController: UIViewController {
        //1.判断是否登录
        if UserAccountViewModel.sharedUserAccount.userLogon {
            return isNewVersion ? NewFeatureViewController() : WelcomeViewController()
        }
        //2.没有登录返回主控制器
        return MainViewController()
    }
    
    /// 判断是否为新版本
    var isNewVersion: Bool {
        //1.当前的版本 - info.plist
        let currentVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
        let version = Double(currentVersion)!
        print("当前版本\(version)")
        
        //2.'之前'的版本,把当前版本保存在用户偏好 -- 如果key不存在，返回0
        let sandboxVersionKey = "sandboxVersionKey"
        let sandboxVersion = UserDefaults.standard.double(forKey: sandboxVersionKey)
        print("之前版本\(sandboxVersion)")
        //3.保存当前版本
        UserDefaults.standard.set(version, forKey: sandboxVersionKey)
        return version > sandboxVersion
    }
    
}
